module FSM(clock, resetN, go, x_ge_y, error_ge_0, drawstate_eq_7, Done, init, E_X_error, E_Y_error, plot, Edrawstate, ps);

	input clock, 
			resetN, 
			go, 
			x_ge_y,
			error_ge_0,
			drawstate_eq_7;
			
	output Done,
			 init,
			 E_X_error,
			 E_Y_error,
			 plot,
			 Edrawstate;
	
	localparam S0 = 3'b000, 
				  S1 = 3'b001,
			  Sdraw = 3'b010,
				  S2 = 3'b011,
				  S3 = 3'b100,
			  Sdone = 3'b101;

	output reg [2:0] ps;
	reg [2:0] ns;
	
	// Main FSM transitions
	always@(*)
		case(ps)
			S0    : if(go) ns = S1; else ns = S0;
			S1    : if(x_ge_y) ns = Sdraw; else ns = Sdone;
			Sdraw : if(drawstate_eq_7) ns = S2; else ns = S1;
			S2    : if(error_ge_0) ns = S3; else ns = S1;
			S3    : ns = S1;
			Sdone : if(go) ns = Sdone; else ns = S0;
			default: ns = 3'bxxx;
		endcase
		
	// FSM state updating
	always@(posedge clock, negedge resetN)
		if(~resetN)
			ps <= S0;
		else
			ps <= ns;
			
	// Control output assignment 
	assign Done       = ps == Sdone,
			 init       = ps == S0,
			 E_X_error  = ps == S3,
			 E_Y_error  = ps == S2,
			 plot       = ps == Sdraw,
			 Edrawstate = ps == S1;

endmodule 